package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.util.GoodCodeMessage;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@RocketMQMessageListener(
        topic = MQCounts.CREATE_ORDER,
        consumerGroup = MQCounts.CREATE_ORDER_GROUP,
        selectorExpression = MQCounts.CREATE_ORDER_TAG
)
public class OrderCreateMQListener implements RocketMQListener<OrderMessage> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void onMessage(OrderMessage orderMessage) {
        System.out.println("创建订单队列");
        Long userId = orderMessage.getUserId();
        Long seckillId = orderMessage.getSeckillId();
        String uuid = orderMessage.getUuid();

        Map<String,Object> data = new HashMap<>();
        data.put("userId", userId);
        data.put("seckillId", seckillId);
        data.put("uuid", uuid);
        try {
            //int a = 4/0;
            String orderNo = orderInfoService.doSeckillOrder(seckillId, userId);
            data.put("data", orderNo);
            data.put("code",200);

            //发送消息到订单成功队列
            rocketMQTemplate.syncSend(MQCounts.ORDER_SUCCESS_DEST,data);
        }catch (Exception e){
            //封装code和msg数据
            data.put("msg",GoodCodeMessage.SECKILL_GOOD_FAIL.getMsg());
            data.put("code",GoodCodeMessage.SECKILL_GOOD_FAIL.getCode());
            //发送消息到失败队列
            rocketMQTemplate.syncSend(MQCounts.ORDER_FAIL_DEST,data);
        }
    }
}
